package {{packageName}}.util.enums;

import cn.ibizlab.util.domain.IEntity;
import cn.ibizlab.util.filter.ISearchContext;
import cn.ibizlab.util.helper.BeanCache;
import cn.ibizlab.util.security.SpringContextHolder;
import lombok.SneakyThrows;
import java.util.Arrays;
import java.util.Optional;

/**
 * 注册实体枚举
 *
 * @author generator
 */
public enum Entities {

{{#each system.entities as |entity|}}
{{#unless (and (eq entity.module 'ibizsysmgr')  (eq entity.codeName 'SysDepartment') )}}
    {{entity.definitionName}} ("{{entity.codeName}}","{{entity.logicName}}",{{packageName}}.core.{{entity.module}}.domain.{{entity.domainClassName}}.class,{{#neq entity.storage 'NONE'}}{{packageName}}.core.{{entity.module}}.filter.{{entity.codeName}}SearchContext.class,{{packageName}}.core.{{entity.module}}.service.{{entity.codeName}}Service.class{{else}}null,null{{/neq}}){{#if @last}};{{else}},{{/if}}
{{/unless}}
{{/each}}

    public final String codeName;
    public final String displayName;
    public final Class<? extends IEntity> entityClass;
    public final Class<? extends ISearchContext> filterClass;
    public final Class<?> serviceClass;

    public BeanCache.BeanSchema getSchema() {
        return BeanCache.get(entityClass);
    }

    @SneakyThrows
    public IEntity newEntityInstance() {
        return entityClass.newInstance();
    }

    @SneakyThrows
    public ISearchContext newFilterInstance() {
        return filterClass.newInstance();
    }

    @SneakyThrows
    public <T> T getService() {
        return (T) SpringContextHolder.getBean(serviceClass);
    }

    private Entities(String codeName, String displayName, Class<? extends IEntity> entityClass, Class<? extends ISearchContext> filterClass, Class serviceClass){
        this.codeName = codeName;
        this.displayName = displayName;
        this.entityClass = entityClass;
        this.filterClass = filterClass;
        this.serviceClass = serviceClass;
    }

    public static Optional<Entities> from(String codeName) {
        return Arrays.stream(Entities.values()).filter(item -> item.codeName.equalsIgnoreCase(codeName)||item.name().equalsIgnoreCase(codeName)||item.codeName.equalsIgnoreCase(codeName.replace("_",""))||item.name().equalsIgnoreCase(codeName+"DTO")||item.name().equalsIgnoreCase(codeName+"FilterDTO")).findFirst();
    }

    @Override
    public String toString() {
        return codeName;
    }

    public boolean equals(String codeName) {
        return this.codeName.equalsIgnoreCase(codeName)||this.name().equalsIgnoreCase(codeName)||this.codeName.equalsIgnoreCase(codeName.replace("_",""));
    }
}
